﻿using System;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Web;
using System.Web.Mvc;
using KPIS.GERP.Models;
using KPIS.GERP.Models.ICM;
using System.Collections.Generic;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    // [AccessDeniedAuthorize]
    public class ReceiveParcelController : Controller
    {
        //
        // GET: /ReceiveParcel/

        #region ReceiveParcel

        public ActionResult Index()
        {
            var service = new ReceiveParcelService.ReceiveParcelServiceClient();
            return View(service.SelectReceived(new Received { RecordStatus = "!D" }, new[] { "Warehouse", "ReceiveType", "DeliveryNote" }));
        }

        public ActionResult Create()
        {
            return View(new Received());
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Received model, int hdWhId)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    model.ReceiveDate = DateTime.Now;
                    model.WhId = hdWhId;

                    var service = new ReceiveParcelService.ReceiveParcelServiceClient();
                    int id = service.Insert(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("Details", new { id = id });
                }
                return View(model);
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Edit(int id)
        {
            var service = new ReceiveParcelService.ReceiveParcelServiceClient();
            var item = service.SelectReceived(new Received { ReceiveId = id }, new[] { "Warehouse", "DeliveryNote" }).FirstOrDefault();

            if (item == null)
            {
                return HttpNotFound();
            }
            ViewBag.State = "Edit";
            return View(item);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Received model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new ReceiveParcelService.ReceiveParcelServiceClient();
                    service.Update(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("Index");
                }
                return Edit(model.ReceiveId);
            }
            catch
            {
                return Edit(model.ReceiveId);
            }
        }

        public ActionResult Delete(int id)
        {
            try
            {
                var service = new ReceiveParcelService.ReceiveParcelServiceClient();
                service.Delete(id, Class.GimsMembership.CurrentEmpId);

                return RedirectToAction("Index");
            }
            catch
            {
                return Index();
            }
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult DeleteAll(int[] deleteIds)
        {
            try
            {
                if (deleteIds != null)
                {
                    var service = new ReceiveParcelService.ReceiveParcelServiceClient();

                    foreach (int delete in deleteIds)
                    {
                        service.Delete(delete, Class.GimsMembership.CurrentEmpId);
                    }
                }

                ModelState.AddModelError("Error", "ลบข้อมูลไปทั้งหมด " + deleteIds.Length.ToString("#,##0") + " รายการ");

                return Json(new { success = true });
            }
            catch
            {
                ModelState.AddModelError("Error", "พบข้อผิดพลาดขณะลบข้อมูล");
                return Json(new { success = false });
            }
        }

        #endregion


        #region ReceiveParcelDtl

        public ActionResult Details(int id)
        {
            var service = new ReceiveParcelService.ReceiveParcelServiceClient();
            var item = service.SelectReceived(new Received { ReceiveId = id, RecordStatus = "!D" }, new[] { "Warehouse", "ReceiveType", "DeliveryNote" }).FirstOrDefault();

            if (item == null)
            {
                return HttpNotFound();
            }
            else
            {
                ViewBag.RecId = id;
                ViewBag.RecType = item.ReceiveTypeId;   // ประเภทพัสดุ
                ViewBag.Receive = item;
            }

            var model = service.SelectReceiveDtl(new ReceiveDtl { ReceiveId = id, RecordStatus = "!D" }, new[] { "MasResourceItem","MasResourceType","MasUnit","MasDepreciationType"});
            return View(model);
        }

        public ActionResult CreateDetails(int id)
        {
            var service = new ReceiveParcelService.ReceiveParcelServiceClient();
            var item = service.SelectReceived(new Received { ReceiveId = id, RecordStatus = "!D" }, null).FirstOrDefault();
            
            if (item == null)
            {
                return HttpNotFound();
            }
            else
            {
                ViewBag.RecType = item.ReceiveTypeId;   // ประเภทการรับพัสดุ
                ViewBag.DnId = item.DnId;
                ViewBag.RecId = id;
                ViewBag.ReceiveDate = item.ReceiveDate;
                ViewBag.WhId = item.WhId;               // คลังที่รับ
                ViewBag.ReceiveDate = item.ReceiveDate; // วันที่รับเข้าคลัง 
            }

            return View(new ReceiveDtl());
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateDetails(ReceiveDtl model,
            int hdRecId, int hdResItemId, string ProjExpId, int hdResTypeId, string hdDnItemId, int hdWhId, int hdSubGrpId, int hdGrpId,
            string txtParcelPrefix,
            int ddlUnit, int txtQuantity, int? txtParcelStartNo, int? txtParcelEndNo, int? ddlDepreciationType,
            int ddlAssetStatus, HttpPostedFileBase file, string txtSerial,
            string txtLotNumber, string txtParcelType, string hdParcelName, string QualityAssuranceExpDate,
            string txtDescription, string txtRemark, string txtAssetDate, string txtLifeYear, 
            int ddlBgSourceId = 0, bool? rdoIsLowerAsset = false, decimal txtPrice = 0)
        {
            var service = new ReceiveParcelService.ReceiveParcelServiceClient();
            var serviceReq = new RequestParcelService.RequestParcelServiceClient();
            var serviceWarehouse = new WarehouseService.WarehouseServiceClient();
            var serviceDn = new DeliveryNoteItemService.DeliveryNoteItemServiceClient();
            var servicePprItem = new PrePurchaseRequestItemService.PrePurchaseRequestItemServiceClient();

            var JobsiteSeq = serviceReq.GetJobsite(Class.GimsMembership.CurrentEmpId);

            int intJobsiteId = Convert.ToInt32(JobsiteSeq[1]);

            int? intProjExpId = null;
            if (ProjExpId != "")
            {
                intProjExpId = Convert.ToInt32(ProjExpId);
            }

            if (rdoIsLowerAsset != true)
            {
                model.DepreciationTypeId = ddlDepreciationType;
            }

            if (ddlBgSourceId == 0)
            {
                ModelState.AddModelError("ddlBgSourceId", "กรุณาเลือกแหล่งเงิน");
            }

            try
            {
                ViewBag.RecId = hdRecId;
                ViewBag.RecType = hdResTypeId;
                ViewBag.WhId = hdWhId;  

                if (ModelState.IsValid)
                {
                    // ReceiveDtl
                    model.ReceiveId = hdRecId;
                    model.ResourceTypeId = hdResTypeId;
                    model.UnitId = ddlUnit;
                    model.BgSourceId = ddlBgSourceId;
                    model.ResourceItemId = hdResItemId;
                    model.Price = txtPrice;
                    model.Remark = txtRemark;
                    model.Description = txtDescription;


                    // แตก DnItem ไปถึง PprItem เพื่อเอา ProjExpId
                    if (hdDnItemId != "")
                    {
                        int DnItemId = Convert.ToInt32(hdDnItemId);
                        var dnItemModel = serviceDn.SelectDeliveryNoteItem(new DeliveryNoteItem() { DnItemId = DnItemId }
                            , new[] { "PoInstallItem.BidderQuotation.PurchaseRequestItem" }).FirstOrDefault();
                        var pprItemModels = servicePprItem.Select(new PrePurchaseRequestItem() { PrItemId = dnItemModel.PoInstallItem.BidderQuotation.PurchaseRequestItem.PrItemId }, new[] { "ProjectOperationExpense.ProjectExpense" });

                        foreach (var pprItemModel in pprItemModels)
                        {
                            model.DeliveryNoteItemId = Convert.ToInt32(hdDnItemId);
                            model.ProjExpId = pprItemModel.ProjectOperationExpense.ProjectExpense.ProjExpId;
                            model.Quantity = pprItemModel.Qty ?? 1;
                            
                            int intReceivDtlId = service.InsertDtl(model, Class.GimsMembership.CurrentEmpId);

                            InsertLotOrAsset(model, pprItemModel, intReceivDtlId
                                , txtParcelType, hdResItemId, hdWhId, ddlBgSourceId, txtLotNumber, txtDescription
                                , txtPrice, txtRemark, ddlUnit, file
                                , ddlDepreciationType, hdResTypeId, ddlAssetStatus, txtParcelPrefix, txtParcelStartNo
                                , hdParcelName, txtAssetDate, txtSerial, QualityAssuranceExpDate
                                , hdSubGrpId, hdGrpId, txtLifeYear, txtQuantity, rdoIsLowerAsset ?? false);

                            if (ViewData["file_error"] != null && ViewData["file_error"].ToString() != "")
                            {
                                return View(model);
                            }
                        }
                    }
                    else
                    {
                        model.DeliveryNoteItemId = 0;
                        model.ProjExpId = null;
                        model.Quantity = txtQuantity;

                        int intReceivDtlId = service.InsertDtl(model, Class.GimsMembership.CurrentEmpId);

                        InsertLotOrAsset(model, null, intReceivDtlId
                            , txtParcelType, hdResItemId, hdWhId, ddlBgSourceId, txtLotNumber, txtDescription
                            , txtPrice, txtRemark, ddlUnit, file
                            , ddlDepreciationType, hdResTypeId, ddlAssetStatus, txtParcelPrefix, txtParcelStartNo
                            , hdParcelName, txtAssetDate, txtSerial, QualityAssuranceExpDate
                            , hdSubGrpId, hdGrpId, txtLifeYear, txtQuantity, rdoIsLowerAsset ?? false);

                        if (ViewData["file_error"] != null && ViewData["file_error"].ToString() != "")
                        {
                            return View(model);
                        }
                    }

                    return RedirectToAction("Details", new { id = hdRecId });
                }  
                return RedirectToAction("CreateDetails", new { id = hdRecId }); 
            }
            catch
            {
                return View();
            }
        }

        public void InsertLotOrAsset(ReceiveDtl model, PrePurchaseRequestItem pprItemModel, int intReceivDtlId
            , string txtParcelType, int hdResItemId, int hdWhId, int ddlBgSourceId, string txtLotNumber, string txtDescription
            , decimal txtPrice, string txtRemark, int ddlUnit, HttpPostedFileBase file
            , int? ddlDepreciationType, int hdResTypeId, int ddlAssetStatus, string txtParcelPrefix, int? txtParcelStartNo
            , string hdParcelName, string txtAssetDate, string txtSerial, string QualityAssuranceExpDate
            , int hdSubGrpId, int hdGrpId, string txtLifeYear, int txtQuantity, bool? rdoIsLowerAsset = false)
        {
            var service = new ReceiveParcelService.ReceiveParcelServiceClient();
            var serviceWarehouse = new WarehouseService.WarehouseServiceClient();

            if (txtParcelType == "วัสดุ")
            {
                OfficeSuppliesLot modelOfficeSuppliesLot = new OfficeSuppliesLot();

                // กรณี: วัสดุ
                modelOfficeSuppliesLot.ResItemId = hdResItemId;
                modelOfficeSuppliesLot.WhId = hdWhId;

                if (pprItemModel != null)
                {
                    modelOfficeSuppliesLot.ProjExpId = pprItemModel.ProjectOperationExpense.ProjectExpense.ProjExpId;
                }
                else
                {
                    modelOfficeSuppliesLot.ProjExpId = null; 
                }
                modelOfficeSuppliesLot.Quantity = txtQuantity;//pprItemModel.Qty ?? 1;

                modelOfficeSuppliesLot.BgSourceId = ddlBgSourceId;
                modelOfficeSuppliesLot.ReceiveDtlId = intReceivDtlId;
                modelOfficeSuppliesLot.LotNo = txtLotNumber;
                modelOfficeSuppliesLot.Description = txtDescription;
                modelOfficeSuppliesLot.Price = txtPrice;
                modelOfficeSuppliesLot.Remark = txtRemark;
                modelOfficeSuppliesLot.UnitId = ddlUnit;

                // OfficeSupplyLotStatusId == 83  >>>   83 คือ สถานะของวัสดุ ว่าใช้งานได้   มาจาก LookUpId ในตาราง IcmMasLookup  มี LookUpType เป็น OfficeSupplyLotStatus
                modelOfficeSuppliesLot.OfficeSupplyLotStatusId = 83;

                ViewData["file_error"] = "";
                if (file != null && file.ContentLength > 0)
                {
                    string file_ext = Path.GetExtension(file.FileName);
                    if (!FileType(file_ext))
                    {
                        ViewData["file_error"] = "การอัพโหลดรูปต้องเป็นประเภท JPEG,PNG หรือ GIF เท่านั้น!";
                        return;
                    }

                    string folder_path = Server.MapPath("~/Content/Ace/assets/OfficeSuppiles");

                    DirectoryInfo di = new DirectoryInfo(folder_path);
                    if (!di.Exists)
                    {
                        System.IO.Directory.CreateDirectory(folder_path);
                        FolderACL("Everyone", folder_path);
                    }

                    var fileName = DateTime.Now.Ticks.ToString() + Path.GetFileName(file.FileName);
                    var path = (folder_path + "/" + fileName);
                    modelOfficeSuppliesLot.PicturePath = Path.Combine(fileName);
                    file.SaveAs(path);
                    fileName = modelOfficeSuppliesLot.PicturePath;
                }

                service.InsertOfficeSupplyLot(modelOfficeSuppliesLot, Class.GimsMembership.CurrentEmpId);
            }
            else
            {
                // กรณี: ครุภัณฑ์ / ที่ดิน / สิ่งก่อสร้าง  
                //for (int i = Convert.ToInt32(txtParcelPrefix); i <= ((txtQuantity + Convert.ToInt32(txtParcelPrefix)) - 1); i++) //txtParcelStartNo
                for (int i = 0; i < (pprItemModel != null ? (pprItemModel.Qty ?? 1) : txtQuantity); i++)
                {
                    Asset modelAsset = new Asset();

                    modelAsset.DepreciationTypeId = ddlDepreciationType;
                    modelAsset.ResItemId = hdResItemId;
                    modelAsset.WhId = hdWhId;
                    modelAsset.AssetTypeId = hdResTypeId;

                    if (pprItemModel != null)
                    {
                        modelAsset.ProjExpId = pprItemModel.ProjectOperationExpense.ProjectExpense.ProjExpId;
                    }
                    else
                    {
                        modelAsset.ProjExpId = null;
                    }

                    DateTime dt = Convert.ToDateTime(txtAssetDate);
                    string strBgmSource = ddlBgSourceId == 1 ? "1" : "2";

                    modelAsset.BgSourceId = ddlBgSourceId;
                    modelAsset.ReceiveDtlId = intReceivDtlId;
                    modelAsset.UnitId = ddlUnit;
                    modelAsset.AssetStatusId = ddlAssetStatus;
                    modelAsset.AssetCode = txtParcelPrefix + ((txtParcelStartNo ?? 0) + i).ToString("000");//เลขที่ครุภัณฑ์
                    modelAsset.AssetName = hdParcelName;
                    modelAsset.AssetDate = dt;
                    modelAsset.SerialNumber = txtSerial;
                    modelAsset.IsLowerAsset = rdoIsLowerAsset??false;
                    modelAsset.Quantity = 1;
                    modelAsset.Price = Convert.ToDouble(txtPrice);
                    modelAsset.Description = txtDescription;

                    if (QualityAssuranceExpDate != "")
                    {
                        modelAsset.QualityAssuranceExpireDate = Convert.ToDateTime(QualityAssuranceExpDate);
                    }

                    modelAsset.Remark = txtRemark;
                    modelAsset.ResSubGrpId = hdSubGrpId;
                    modelAsset.ResGrpId = hdGrpId;
                    modelAsset.Place = serviceWarehouse.Select(new Warehouse() { WhId = hdWhId }, null).FirstOrDefault().Name;

                    if (txtLifeYear != "")
                    {
                        modelAsset.LifeYear = Convert.ToInt32(txtLifeYear);
                    }

                    ViewData["file_error"] = "";
                    if (file != null && file.ContentLength > 0)
                    {
                        string file_ext = Path.GetExtension(file.FileName);
                        if (!FileType(file_ext))
                        {
                            ViewData["file_error"] = "การอัพโหลดรูปต้องเป็นประเภท JPEG,PNG หรือ GIF เท่านั้น!";
                            return;
                        }

                        string folder_path = Server.MapPath("~/Content/Ace/assets/Asset");
                        DirectoryInfo di = new DirectoryInfo(folder_path);

                        if (!di.Exists)
                        {
                            System.IO.Directory.CreateDirectory(folder_path);
                            FolderACL("Everyone", folder_path);
                        }

                        var fileName = DateTime.Now.Ticks.ToString() + Path.GetFileName(file.FileName);
                        var path = (folder_path + "/" + fileName);
                        modelAsset.PicturePath = Path.Combine(fileName);
                        file.SaveAs(path);
                        fileName = modelAsset.PicturePath;
                    }

                    int intAssetId = service.InsertAsset(modelAsset, Class.GimsMembership.CurrentEmpId);
                }
            }
        }
        
        public ActionResult DeleteDtl(int id, int intRecId)
        {
            try
            {
                var service = new ReceiveParcelService.ReceiveParcelServiceClient();
                service.DeleteDtl(id, Class.GimsMembership.CurrentEmpId);

                return RedirectToAction("Details", new { id = intRecId });
            }
            catch
            {
                return null;
            }
        }

        #endregion


        #region UploadFile

        public static void FolderACL(String accountName, String folderPath)
        {
            FileSystemRights Rights;

            //What rights are we setting?
            Rights = FileSystemRights.FullControl;
            bool modified;
            InheritanceFlags none = new InheritanceFlags();
            none = InheritanceFlags.None;

            //set on dir itself
            FileSystemAccessRule accessRule = new FileSystemAccessRule(accountName, Rights, none, PropagationFlags.NoPropagateInherit, AccessControlType.Allow);
            DirectoryInfo dInfo = new DirectoryInfo(folderPath);
            DirectorySecurity dSecurity = dInfo.GetAccessControl();
            dSecurity.ModifyAccessRule(AccessControlModification.Set, accessRule, out modified);

            //Always allow objects to inherit on a directory 
            InheritanceFlags iFlags = new InheritanceFlags();
            iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;

            //Add Access rule for the inheritance
            FileSystemAccessRule accessRule2 = new FileSystemAccessRule(accountName, Rights, iFlags, PropagationFlags.InheritOnly, AccessControlType.Allow);
            dSecurity.ModifyAccessRule(AccessControlModification.Add, accessRule2, out modified);

            dInfo.SetAccessControl(dSecurity);
        }

        public bool FileType(String file_extentions)
        {
            bool ret = false;

            if (file_extentions.ToLower().StartsWith(".jpg"))
                ret = true;
            else if (file_extentions.ToLower().StartsWith(".png"))
                ret = true;
            else if (file_extentions.ToLower().StartsWith(".gif"))
                ret = true;
            else
                ret = false;

            return ret;
        }

        #endregion


        #region SubDetails

        public ActionResult SubDetails(int id, int? intAssetId)
        {
            var service = new ReceiveParcelService.ReceiveParcelServiceClient();
            var item = service.SelectReceiveDtl(new ReceiveDtl { ReceiveDtlId = id, RecordStatus = "!D" }, null).FirstOrDefault();
            
            string strAssetId;
            if (intAssetId == null)
            {
                strAssetId = "0";
            }
            else
            {
                strAssetId = intAssetId.ToString();
            }

            if (item == null)
            {
                return HttpNotFound();
            }
            else
            {
                ViewBag.RecDtlId = id.ToString();// ReceiveDtlId
                ViewBag.ResTypeId = item.ResourceTypeId.ToString();
                ViewBag.RecId = item.ReceiveId.ToString();
                ViewBag.AssetId = strAssetId;
            }

            return View();
        }

        #endregion


        #region Warranty

        [HttpPost]
        public ActionResult CreateWarranty(string strNo, decimal decPrice, int intTime, string strStart, string strEnd, int intType, int intId, int intRecDtlId)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new ReceiveParcelService.ReceiveParcelServiceClient();

                    int intCreateBy = Class.GimsMembership.CurrentEmpId;

                    service.InsertWarranty(intId, strNo, decPrice, intTime, strStart, strEnd, intCreateBy);

                    //return RedirectToAction("SubDetails", intRecDtlId);
                    return Json(new { success = true });
                }
                return null;
            }
            catch
            {
                return null;
            }
        }

        public ActionResult DeleteWarranty(int id, int intAssetId, int intDtlId)
        {
            try
            {
                var service = new ReceiveParcelService.ReceiveParcelServiceClient();
                service.DeleteWarranty(id, Class.GimsMembership.CurrentEmpId);

                return RedirectToAction("SubDetails", new { id = intDtlId, intAssetId = intAssetId });
            }
            catch
            {
                return null;
                //return View("IndexMovementDtl", new { MovementId = movementId });
            }
        }

        #endregion


        #region GetInfo

        public ActionResult GetInfoParcel(int intDnItem, string ReceiveDate)
        {
            DateTime dtReceiveDate = Convert.ToDateTime(ReceiveDate);
            var service = new ReceiveParcelService.ReceiveParcelServiceClient();
            var serviceDnItem = new DeliveryNoteItemService.DeliveryNoteItemServiceClient();
            var servicePrItem = new PurchaseRequestItemService.PurchaseRequestItemServiceClient();
            var servicePprItem = new PrePurchaseRequestItemService.PrePurchaseRequestItemServiceClient();
            var serviceAsset = new AssetService.AssetServiceClient();
            var serviceOrder = new PurchaseOrderService.PurchaseOrderServiceClient();

            var modelDnItem = serviceDnItem.SelectDeliveryNoteItem(new DeliveryNoteItem() { DnItemId = intDnItem , RecordStatus = "!"+ Models.SYS.RecordStatus.DeletedStatus }
                , new[] { "MasResourceItem.MasResourceSubGroup.MasResourceGroup.MasResourceType"
                    , "DeliveryNote.PurchaseOrder.Bidder.PurchaseRequest", "MasResourceItem.MasUnit"
                    , "PoInstallItem"}).FirstOrDefault();
            if (modelDnItem != null)
            {
                var PrItemId = servicePrItem.Select(new PurchaseRequestItem() { PrId = modelDnItem.DeliveryNote.PurchaseOrder.Bidder.PurchaseRequest.PrId }, null).FirstOrDefault().PrItemId;
                var InstallmentItems = serviceOrder.SelectPoInstallmentItem(new PurchaseOrderInstallmentItem() { BidderQuoId = modelDnItem.PoInstallItem.BidderQuoId }, null).ToList();
                var NoItemDnItems = new List<DeliveryNoteItem>();
                var modelPprItem = servicePprItem.Select(new PrePurchaseRequestItem() { PrItemId = PrItemId }
                        , new[] { "ProjectOperationExpense.ProjectExpense.Project" }).FirstOrDefault();
                //var info = service.GetParcelInformation(intDnItem);
                double dPrice2 = 0;

                foreach (var InstallmentItem in InstallmentItems)
                {
                    var NoItemDnItem = serviceDnItem.SelectDeliveryNoteItem(new DeliveryNoteItem() { PoInstallItemId = InstallmentItem.PoInstallItemId, HaveItem = false }, null).FirstOrDefault();

                    if (NoItemDnItem != null && NoItemDnItem.DnItemId != modelDnItem.DnItemId)
                    {
                        NoItemDnItems.Add(NoItemDnItem);
                    }
                }

                if (NoItemDnItems.Count > 0)
                {
                    dPrice2 = NoItemDnItems.Sum(m => m.ItemPriceExcludeVat) ?? 0;
                }

                int nYear = 0;

                if (dtReceiveDate.Month > 9)
                {
                    nYear = dtReceiveDate.Year + 544;
                }
                else
                {
                    nYear = dtReceiveDate.Year + 543;
                }

                string strResItemType = modelDnItem.MasResourceItem.MasResourceSubGroup.MasResourceGroup.MasResourceType.Name;
                string strResItemCode = (modelPprItem.ProjectOperationExpense.ProjectExpense.BgSourceId == 1 ? "1" : "2") + modelDnItem.MasResourceItem.Code + nYear.ToString("00").Substring(2);
                string strMaxCode = string.Empty;
                if (strResItemType == "วัสดุ")
                {
                    strMaxCode = service.MaxCodeOfficeSupplyLot(strResItemCode); 
                }
                else
                {
                    strMaxCode = service.MaxCodeAsset(strResItemCode); //serviceAsset.SelectAsset(new Asset() { AssetCode = strResItemCode }).FirstOrDefault().AssetCode;
                }
                string strRunning = "";

                if (string.IsNullOrWhiteSpace(strMaxCode))
                {
                    strRunning = "001";
                }
                else
                {
                    int nRunning = 0;

                    int.TryParse(strMaxCode.Substring(strMaxCode.Length - 3), out nRunning);

                    strRunning = (nRunning + 1).ToString("000");
                }

                string description = "";
                 

                return Json(new
                {
                    BgSourceId = modelPprItem.ProjectOperationExpense.ProjectExpense.BgSourceId,
                    UnitId = modelDnItem.MasResourceItem.UnitId,
                    UnitName = modelDnItem.MasResourceItem.MasUnit.Name,
                    ResTypeId = modelDnItem.MasResourceItem.MasResourceSubGroup.MasResourceGroup.MasResourceType.ResTypeId,
                    ResTypeName = modelDnItem.MasResourceItem.MasResourceSubGroup.MasResourceGroup.MasResourceType.Name,
                    ProjExpId = modelPprItem.ProjectOperationExpense.ProjExpId,
                    ProjName = modelPprItem.ProjectOperationExpense.ProjectExpense.Project.Name,
                    Price = ((modelDnItem.ItemPriceExcludeVat ?? 0) + dPrice2).ToString("#,##0.00"),
                    ResItemId = modelDnItem.ResItemId,
                    ResSubGrpId = modelDnItem.MasResourceItem.ResSubGrpId,
                    ResGrpId = modelDnItem.MasResourceItem.MasResourceSubGroup.ResGrpId,
                    Quantity = modelDnItem.ItemQty,
                    LotNo = strResItemCode + strRunning,
                    DnCode = modelDnItem.DeliveryNote.Code,
                    Running = strRunning,
                    ResItemCode = strResItemCode,
                    Description = modelPprItem.Descr
                }, JsonRequestBehavior.AllowGet);
            }
            return Json(new
            {
                MsgText = "false",
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetWarehouse(int intDnId)
        {
            var service = new ReceiveParcelService.ReceiveParcelServiceClient();
            var WhInfo = service.GetWarehouse(intDnId);

            if (WhInfo != null)
            {
                return Json(new
                {
                    Id = WhInfo[0],
                    Name = WhInfo[1]
                }, JsonRequestBehavior.AllowGet);
            }

            return View();
        }
        
        public ActionResult GetDpRate(int intDpTypeId)
        {
            var service = new ReceiveParcelService.ReceiveParcelServiceClient();
            var DpRate = service.GetDpRate(intDpTypeId);

            if (DpRate != null)
            {
                return Json(new
                {
                    Rate = DpRate[0],
                    MinLife = DpRate[1],
                    MaxLife = DpRate[2]
                }, JsonRequestBehavior.AllowGet);
            }

            return View();
        }
        
        //public ActionResult GetLastAssetPK()
        //{
        //    int intAssetPk = 0;
        //    var service = new ReceiveParcelService.ReceiveParcelServiceClient();
        //    var Asset = service.SelectAsset(new Models.ICM.Asset { RecordStatus = "!D" }, null).OrderByDescending(x => x.AssetId).FirstOrDefault();
            
        //    if (Asset != null)
        //    {
        //        intAssetPk = Asset.AssetId;
        //        return Json(new { PK = intAssetPk }, JsonRequestBehavior.AllowGet);
        //    }
        //    else {
        //        return Json(new { PK = intAssetPk }, JsonRequestBehavior.AllowGet);
        //    }
        //}

        public ActionResult GetResourceGroup(int intResType)
        {
            var service = new KPIS.GERP.WEB.GIMS.ReceiveParcelService.ReceiveParcelServiceClient();
            var Group = service.SelectListMasResourceGroup(new MasResourceGroup { ResTypeId=intResType, RecordStatus = "!D" });
            return this.Json(Group, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetResourceSubGroup(int intResGroup)
        {
            var service = new KPIS.GERP.WEB.GIMS.ReceiveParcelService.ReceiveParcelServiceClient();
            var SubGroup = service.SelectListMasResourceSubGroup(new MasResourceSubGroup { ResGrpId = intResGroup, RecordStatus = "!D" });
            return this.Json(SubGroup, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetResourceItem(int intResSubGroup)
        {
            var service = new KPIS.GERP.WEB.GIMS.ReceiveParcelService.ReceiveParcelServiceClient();
            var Item = service.SelectListMasResourceItem(new MasResourceItem { ResSubGrpId = intResSubGroup, RecordStatus = "!D" });

            return this.Json(Item, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetInfoItem(int intResItemId, string strReceiveDate)
        {
            DateTime ReceiveDate = Convert.ToDateTime(strReceiveDate);
            var service = new KPIS.GERP.WEB.GIMS.ReceiveParcelService.ReceiveParcelServiceClient();
            var Item = service.GetParcelInfo(intResItemId);

            int nYear = 0;

            if (ReceiveDate.Month > 9)
            {
                //nYear = ReceiveDate.Year + 1;
                nYear = ReceiveDate.Year + 544;
            }
            else
            {
                //nYear = ReceiveDate.Year;
                nYear = ReceiveDate.Year + 543;
            }
            string strResTypeName = Item[3];
            string strResItemCode = Item[2] + nYear.ToString("00").Substring(2); //Item[2] + "-" + nYear.ToString("0000").Substring(2) + "-";
            string strMaxCode = string.Empty;
            if (strResTypeName == "วัสดุ")
            {
                strMaxCode = service.MaxCodeOfficeSupplyLot(strResItemCode); 
            }
            else
            { 
                strMaxCode = service.MaxCodeAsset(strResItemCode); //serviceAsset.SelectAsset(new Asset() { AssetCode = strResItemCode }).FirstOrDefault().AssetCode;
            }

            string strRunning = "";

            if (string.IsNullOrWhiteSpace(strMaxCode))
            {
                strRunning = "001";
            }
            else
            {
                int nRunning = 0;

                int.TryParse(strMaxCode.Substring(strMaxCode.Length - 3), out nRunning);

                strRunning = (nRunning + 1).ToString("000");
            }


            if (Item != null)
            {
                return Json(new
                {
                    GrpId = Item[0],
                    SubGrpId = Item[1],
                    Running = strRunning,
                    ResItemCode = strResItemCode,
                    LotNo = strResItemCode + strRunning,

                }, JsonRequestBehavior.AllowGet);
            }

            return Json(new
            {
                GrpId = "",
                SubGrpId = "",
                Running = strRunning,
                ResItemCode = strResItemCode,
                LotNo = strResItemCode + strRunning,
            }, JsonRequestBehavior.AllowGet);
        }

        #endregion

       
    }
}
   
